package com.bjc.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @program: servlet
 * @description:
 * @author: bjc
 * @create: 2021-08-23 21:19
 */
public class OneFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpSession session = null;

        //1.请求对象读取请求包中请求行的URI，了解用户访问的资源文件是谁
        String uri = request.getRequestURI();
        if (uri.indexOf("login")!=-1 || "/myWeb/".equals(uri)){
            //放行login 和/myWeb/请求
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        //2.如果访问的是其他资源文件 进行拦截，拦截后，通过请求对象向tomcat索要当前用户的HttpSession
        session = request.getSession(false);
        //3.判断来访用户身份合法性
        if (session == null) {
            //不合法，进行拦截
            request.getRequestDispatcher("/login_error.html").forward(servletRequest,servletResponse);
            return;
        }
        //4.放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
